<?php
class Lottery extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->library('pagination');
        $this->load->model('activity_lottery_model', 'activity_lottery');
        $this->load->model('user_lottery_model', 'user_lottery');
        $this->load->model('lottery_winner_model', 'lottery_winner');
        $this->load->model('express_model', 'express');
        $this->load->model('express_record_model', 'express_record');
        $this->load->model('user_model', 'user');
        $this->load->model('lottery_reseller_model', 'lottery_reseller');
    }

    /**
     * 抽奖活动列表
     */
    public function index($pg = 1)
    {
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url'] = base_url('lottery/index').$this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('lottery/index');
        $config['total_rows'] = $this->activity_lottery->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['page_list'] = $this->activity_lottery->page_list($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $this->load->view('lottery/index', $data);
    }

    /**
     * 添加活动
     */
    public function addLottery()
    {
        $this->load->view('lottery/addLottery');
    }

    /**
     * 编辑活动
     */
    public function editLottery($id)
    {
        $result = $this->lotteryExists($id);
        if ($result === FALSE) {
            $this->error('lottery/index', '', '活动不存在');
        }
        $data['lottery'] = $result;
        $data['reseller'] = $this->lottery_reseller->findByLotteryId($id);
        $this->load->view('lottery/editLottery', $data);
    }

    public function deleteLottery($id)
    {
        if ( !$id) {
            $this->error('lottery/index', '', '活动不存在');
        }
        $result = $this->activity_lottery->deleteLottery($id, $this->uid);
        if ( !$result) {
            $this->error('lottery/index', '', '数据异常');
        }
        $this->redirect('lottery/index');
    }

    private function vailLottery()
    {
        $postData = $this->input->post();
        $url = isset($postData['prize_id']) ? 'lotteryprize/editPrize/'.$postData['prize_id'] : 'lotteryprize/addPrize';
        if ( !isset($postData['lottery_name']) || mb_strlen($postData['lottery_name']) > 60) {
            $this->error($url, '', '请输入活动名称,字数为6-60位');
        }

        if ($postData['on_line'] == 2 && !empty($postData['reseller_name'])) {
            $resellerName = array_filter($postData['reseller_name']);
            $user = $this->user->findByParam(array('usernames'=> $resellerName, 'user_type' => 4096));
            if ($user->num_rows() == 0  || $user->num_rows() != count($resellerName)) {
                $this->ajaxJson(false, '请输入活动名称,字数为6-60位');
            }
            $username = array();
            foreach ($user->result() as $value) {
                $username[$value->uid] = $value->user_name;
            }
            $diff = array_diff($resellerName, $username);
            if ( !empty($diff)) {
                $this->ajaxJson(false, '请输入活动名称,字数为6-60位');
            }
        }

        if ( !isset($postData['lottery_sum']) || $postData['lottery_sum'] < 0 || $postData['lottery_sum'] >= 100) {
            $this->ajaxJson(false, '请输入抽奖次数，抽奖次数1-99');
        }

        if ( !isset($postData['winning_num']) || $postData['winning_num'] < 0|| $postData['winning_num'] >= 100) {
            $this->ajaxJson(false, '请输入中奖次数，中奖次数1-99');
        }

        if ( !isset($postData['winning_num']) || $postData['winning_num'] < 0|| $postData['winning_num'] >= 100) {
            $this->ajaxJson(false, '请输入中奖次数，中奖次数1-99');
        }

        $postData['titles'] = json_encode(array(
            'title1' => isset($postData['title1']) ? $postData['title1'] : '',
            'title2' => isset($postData['title2']) ? $postData['title2'] : '',
            'title3' => isset($postData['title3']) ? $postData['title3'] : ''
        ));

        $postData['details'] = json_encode(array(
            'links'   => isset($postData['links']) ? $postData['links'] : '',
            'content' => isset($postData['content']) ? $postData['content'] : ''
        ));

        $postData['winners_details_pages'] = json_encode(array(
            'bonus_links' => isset($postData['bonus_links']) ? $postData['bonus_links'] : ''
        ));

        $postData['uid'] = $this->uid;
        $postData['user_name'] = $this->userName;
        if ( !empty($username)) {
            $postData['reseller'] = $username;
        }
        return $postData;
    }

    public function lotteryEditPost()
    {
        $postData = $this->vailLottery();
        $postData['ad_image1'] = $postData['oldfilename1'];
        if(!empty($_FILES['ad_image1']['name'])){
            $oldfilename1 = empty($postData['oldfilename1']) ? '' : $postData['oldfilename1'];
            $imageData = $this->dealWithImages('ad_image1', $oldfilename1, 'lotteryPrize');
            if ($imageData == false) {
                $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '图片上传失败！');
            }
            $ifResize = $this->dealWithImagesResize($imageData, 640, 80);
            if ($ifResize == false) {
                $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '图片上传失败！');
            }
            $postData['ad_image1'] = $imageData['file_name'];
        }

        $postData['ad_image2'] = $postData['oldfilename2'];
        if(!empty($_FILES['ad_image2']['name'])) {
            $oldfilename2 = empty($postData['oldfilename2']) ? '' : $postData['oldfilename2'];
            $imageData1 = $this->dealWithImages('ad_image2', $oldfilename2, 'lotteryPrize');
            if ($imageData1 == false) {
                $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '图片上传失败！');
            }
            $ifResize = $this->dealWithImagesResize($imageData1, 576, 153);
            if ($ifResize == false) {
                $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '缩略图生成失败！');
            }
            $postData['ad_image2'] = $imageData1['file_name'];
        }

        $postData['adverts'] = json_encode(array(
            'ad_links1' => $postData['ad_links1'],
            'ad_image1' => $postData['ad_image1'],
            'ad_links2' => $postData['ad_links2'],
            'ad_image2' => $postData['ad_image2']
        ));

        if ( !$postData['lottery_id']) {
            $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '操作异常');
        }
        $this->lottery_reseller->delete($postData['lottery_id']);
        if ( !empty($postData['reseller'])) {
            $this->lottery_reseller->insertBatch($postData['lottery_id'], $postData['reseller']);
        }
        $flag = $this->activity_lottery->updateLottery($postData);
        $this->setActivityLotteryCache($postData['lottery_id']);


        if ($flag) {
            $this->success('lottery/index', '', '操作成功');
        } else {
            $this->error('lottery/editLottery/'. $postData['lottery_id'], '', '数据异常');
        }
    }

    /**
     * 活动提交
     */
    public function lotteryAddPost()
    {
        $postData = $this->vailLottery();
        if(!empty($_FILES['ad_image1']['name'])) {
            $imageData = $this->dealWithImages('ad_image1', '', 'lotteryPrize');
            if ($imageData == false) {
                $this->error('lottery/addLottery', '', '图片上传失败！');
            }
            $ifResize = $this->dealWithImagesResize($imageData, 640, 80);
            if ($ifResize == false) {
                $this->error('lottery/addLottery', '', '缩略图生成失败！');
            }
            $postData['ad_image1'] = $imageData['file_name'];
        }

        if(!empty($_FILES['ad_image2']['name'])){
            $imageData1 = $this->dealWithImages('ad_image2', '', 'lotteryPrize');
            if ($imageData1 == false) {
                $this->error('lottery/addLottery', '', '图片上传失败！');
            }
            $ifResize = $this->dealWithImagesResize($imageData1, 576, 153);
            if ($ifResize == false) {
                $this->error('lottery/addLottery', '', '缩略图生成失败！');
            }
            $postData['ad_image2'] = $imageData1['file_name'];
        }

        $postData['adverts'] = json_encode(array(
            'ad_links1' => isset($postData['ad_links1']) ? $postData['ad_links1'] : '',
            'ad_image1' => isset($postData['ad_image1']) ? $postData['ad_image1'] : '',
            'ad_links2' => isset($postData['ad_links2']) ? $postData['ad_links2'] : '',
            'ad_image2' => isset($postData['ad_image2']) ? $postData['ad_image2'] : ''
        ));

        $insertId = $this->activity_lottery->insertLottery($postData);
        if ( !empty($postData['reseller'])) {
            $this->lottery_reseller->insertBatch($insertId, $postData['reseller']);
        }

        if ($insertId) {
            $this->success('lottery/index', '', '操作成功');
        } else {
            $this->error('lottery/addLottery', '', '数据异常');
        }
    }

    /**
     * 设置活动缓存
     */
    private function setActivityLotteryCache($lotteryId)
    {
        if ($lotteryId) {
            $result = $this->activity_lottery->findLotteryCache($lotteryId, $this->uid);
            if ($result->num_rows() > 0) {
                $lottery = $result->row();
                $this->cache->memcached->save('activityLottery'. $lottery->lottery_id, $lottery, 24 * 60 * 60); //设置抽奖活动缓存
                return TRUE;
            }
            $this->cache->memcached->delete('activityLottery'. $lotteryId); //删除缓存
        }
    }

    /**
     * 验证抽奖活动是否存在
     */
    private function lotteryExists($lotteryId)
    {
        if ( !$lotteryId) {
            return FALSE;
        }
        $result = $this->activity_lottery->findByLotteryId($lotteryId, $this->uid);
        if ($result->num_rows() == 0) {
            return FALSE;
        }
        return $result->row();
    }

    //参与用户
    public function userParticipation($pg = 1)
    {
        $lottery = $this->activity_lottery->findByUid($this->uid);
        if ($lottery->num_rows() > 0) {
            $getData = $this->input->get();

            $lotteryIds = array();
            foreach ($lottery->result() as $key => $value) {
                $lotteryIds[] = $value->lottery_id;
            }
            if ( !empty($getData['lottery_id']) && in_array($getData['lottery_id'], $lotteryIds)) {
                $getData['lottery_id'] = $getData['lottery_id'];
            } else {
                $getData['lottery_id'] = $lotteryIds;
            }

            $page_num = 15;
            $num = ($pg-1)*$page_num;
            $config['first_url'] = base_url('lottery/userParticipation').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('lottery/userParticipation');
            $config['total_rows'] = $this->user_lottery->total($getData);
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_link'] = $this->pagination->create_links();
            $data['page_list'] = $this->user_lottery->page_list($page_num, $num, $getData);
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['pg_num'] = $page_num;
            $data['lottery'] = $lottery->result();
        } else {
            $data['all_rows'] = 0;
        }
        $this->load->view('lottery/userParticipation', $data);
    }

    //中奖用户
    public function winners($pg = 1)
    {
        $lottery = $this->activity_lottery->findByUid($this->uid);
        if ($lottery->num_rows() > 0) {
            $getData = $this->input->get();
            $lotteryIds = array();
            $lotteryResult = array();
            foreach ($lottery->result() as $key => $value) {
                $lotteryIds[] = $value->lottery_id;
                $lotteryResult[$value->lottery_id] = $value->lottery_name;
            }
            if ( !empty($getData['lottery_id']) && in_array($getData['lottery_id'], $lotteryIds)) {
                $getData['lottery_id'] = $getData['lottery_id'];
            } else {
                $getData['lottery_id'] = $lotteryIds;
            }

            $page_num = 15;
            $num = ($pg-1)*$page_num;
            $config['first_url'] = base_url('lottery/winners').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('lottery/winners');
            $config['total_rows'] = $this->lottery_winner->total($getData);
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_link'] = $this->pagination->create_links();
            $data['page_list'] = $this->lottery_winner->page_list($page_num, $num, $getData);
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['pg_num'] = $page_num;
            $data['lotteryResult'] = $lotteryResult;
        } else {
            $data['all_rows'] = 0;
        }
        $this->load->view('lottery/winners', $data);
    }

    /**
     * 中奖者详情
     */
    public function winnersDetails($id)
    {
        if ( empty($id)) {
            $this->error('lottery/winners', '', '中奖者不存在');
        }
        $winners = $this->lottery_winner->findById($id);
        if ($winners->num_rows() == 0) {
            $this->error('lottery/winners', '', '中奖者不存在');
        }
        $data['expressAll'] = $this->express->findAll();
        $data['winners'] = $winners->row();
        $this->load->view('lottery/winnersDetails', $data);
    }

    /**
     * 处理完成填写 快递单号
     */
    public function updateWinners()
    {
        $postData = $this->input->post();
        if ( empty($postData['id'])) {
            $this->ajaxJson(false, '中奖信息不存在');
        }
        $winners = $this->lottery_winner->findOneWinner($postData['id']);
        if ($winners->num_rows() == 0) {
            $this->ajaxJson(false, '中奖信息不存在');
        }
        $winners = $winners->row();

        //如果未领
        if ($winners->status == 1) {
            $this->ajaxJson(false, '中奖信息异常');
        }

        $this->db->trans_begin(); //开启事务

        if ( empty($winners->express_num) || $winners->express_num != $postData['express_num']) {
            $result = $this->expressSend();
            if ($result) {
                $this->ajaxJson(false, $result);
            }
        }

        $data = array('express_num' => $postData['express_num']);
        if ($winners->status == 2) {
            $data['status'] = 3;
        }
        $isUpdate = $this->lottery_winner->updateWinner($postData['id'], $data);
        if ($this->db->trans_status() === FALSE  || !$isUpdate) {
            $this->db->trans_rollback();
            $this->ajaxJson(false, '操作失败');
        } else {
            $this->db->trans_commit();
            $this->ajaxJson(true, site_url('lottery/winners'));
        }
    }

    /**
     * 收入快递单号
     */
    public function expressSend()
    {
        $company = trim($this->input->post('company'));
        $number = trim($this->input->post('express_num'));

        if ( !validExpressNu($number)) {
            return '快递单号只能是5位以上的数字、字母组成';
        }
        $expressRecord = $this->express_record->findByNu($number);
        if ($expressRecord->num_rows() > 0) {
            return FALSE;
        }

        $this->load->library('express', null, 'expressLibrary');
        $result = $this->expressLibrary->send($company, $number);
        if (!$result) {
            return '发货失败('.$this->expressLibrary->getMessage().')';
        }

        $express = $this->express->findByName($company)->row(); //查询快递名称
        $data = [
            'name'    => $express->name,
            'company' => $company,
            'number'  => $number,
            'ischeck' => -1,
            'state'   => -1,
            'context' => '',
            'create_at' => date('Y-m-d H:i:s')
        ];
        $resultId = $this->express_record->insert($data);
        if ( !$resultId) {
            return '发货失败(数据插入失败)';
        }
        return FALSE;
    }

    /**
     * 处理虚拟奖品 只需更改状态
     */
    public function virtualPrizes($id)
    {
        if ( empty($id)) {
            $this->error('lottery/winners', '', '中奖者不存在');
        }
        $winners = $this->lottery_winner->findById($id);
        if ($winners->num_rows() == 0) {
            $this->error('lottery/winners', '', '中奖者不存在');
        }
        $winners = $winners->row();

        //如果不是已领
        if ($winners->status != 2) {
            $this->error('lottery/winners', '', '中奖信息异常');
        }
        $isUpdate = $this->lottery_winner->updateStatus($winners->id);

        if ( !$isUpdate) {
            $this->error('lottery/winners', '', '数据异常');
        } else {
            $this->success('lottery/winners', '', '操作成功');
        }
    }

    /**
     * 统计
     */
    public function userLottery($pg = 1)
    {
         $lottery = $this->activity_lottery->findByUid($this->uid);
        if ($lottery->num_rows() > 0) {
            $getData = $this->input->get();
            $lotteryIds = array();
            $lotteryResult = array();
            foreach ($lottery->result() as $key => $value) {
                $lotteryIds[] = $value->lottery_id;
                $lotteryResult[$value->lottery_id] = $value->lottery_name;
            }
            if ( !empty($getData['lottery_id']) && in_array($getData['lottery_id'], $lotteryIds)) {
                $getData['lottery_id'] = $getData['lottery_id'];
            } else {
                $getData['lottery_id'] = $lotteryIds;
            }

            $page_num = 15;
            $num = ($pg-1)*$page_num;
            $config['first_url'] = base_url('lottery/userLottery').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('lottery/userLottery');
            $config['total_rows'] = $this->user_lottery->statisticsTotal($getData);
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_link'] = $this->pagination->create_links();
            $data['page_list'] = $this->user_lottery->statisticsList($page_num, $num, $getData);
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['pg_num'] = $page_num;
            $data['lotteryResult'] = $lotteryResult;
        } else {
            $data['all_rows'] = 0;
        }
        $this->load->view('lottery/userLottery', $data);
    }
}
?>